#pragma once

static UINT64 BASE64_ENC(BYTE const* in, UINT64 in_len, char* out, BOOL RFC_822 = FALSE)
{
	static const char ET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
	UINT64 t = (in_len / 3) * 3;
	UINT64 offset = 0;
	UINT i = 0;
	for (; i < t; i += 3)
	{
		out[offset++] = ET[in[i] >> 2];
		out[offset++] = ET[((in[i] << 4) | (in[i + 1] >> 4)) & 0x3F];
		out[offset++] = ET[((in[i + 1] << 2) | (in[i + 2] >> 6)) & 0x3F];
		out[offset++] = ET[in[i + 2] & 0x3F];
		if (RFC_822 && ((i + 3) % 57) == 0)
		{
			out[offset++] = '\r';
			out[offset++] = '\n';
		}
	}
	switch (in_len % 3)
	{
	case 1:
	{
		out[offset++] = ET[(in[i] & 0xFC) >> 2];
		out[offset++] = ET[(in[i] & 0x03) << 4];
		out[offset++] = '=';
		out[offset++] = '=';
		break;
	}
	case 2:
	{
		out[offset++] = ET[(in[i] & 0xFC) >> 2];
		out[offset++] = ET[((in[i] & 0x03) << 4) | (in[i + 1] >> 4)];
		out[offset++] = ET[(in[i + 1] & 0x0F) << 2];
		out[offset++] = '=';
	}
	}
	out[offset] = 0;
	return offset;
}

static UINT64 BASE64_DEC(char const * in, BYTE* out)
{
	static char const DT[] =
	{
		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63,
		52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3,
		4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
		24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
		38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
	};
	UINT64 len = strlen(in);
	UINT64 in_offset = 0;
	UINT64 out_offset = 0;
	UINT tmp;
	while (in_offset < len)
	{
		if (in[in_offset] == '\r' || in[in_offset] == '\n' || in[in_offset] == '=')
		{
			++in_offset;
			continue;
		}
		tmp = DT[in[in_offset++]] << 18;
		tmp |= DT[in[in_offset++]] << 12;
		out[out_offset++] = tmp >> 16;
		if (in_offset < len && in[in_offset] != '=')
		{
			tmp |= DT[in[in_offset++]] << 6;
			out[out_offset++] = tmp >> 8;
			if (in_offset < len && in[in_offset] != '=')
			{
				tmp |= DT[in[in_offset++]];
				out[out_offset++] = tmp;
			}
		}
	}
	return out_offset;
}